'use strict';

var http = require('http'),
	globals = require('./globals.js'),
	Router = require('./router.js'),
	build_route = require('./route.js'),
	req = require('./request.js'),
	methods = require('methods');

var app = exports = module.exports = {};
app.server = http.createServer();
app.server.on('request', httpServer);
app.baseUrl = '';
app.routetable = {};
app.request = req;

/**
 * Start the server at the specified port
 * @param  {} port
 */
app.server.start = function(port){
	app.server.listen(port);
	console.log('Server listening to port' + port);
};

/**
 * Set The BaseUrl for the app Ex: /api/
 * @param  {} baseurl
 */
app.setbaseUrl = function(baseurl){
	if (baseurl !== '' && baseurl !== undefined && baseurl !== null){
		app.baseUrl = baseurl;
		app.actions = new action.actions(app.baseurl);
	}
};

methods.forEach(function(method)
{
	app[method] = function(controller, action, args)
	{
		var url = '/' + controller + '/' + action + ((args !== undefined && args !== null && args !== '')? args : '');
		if(app.routetable === undefined || app.routetable === null || !app.routetable.hasOwnProperty(args) || !app.routetable[args].hasOwnProperty('formMethod') || app.routetable[args].formMethod === null || app.routetable[args].formMethod === undefined || app.routetable[args].formMethod.toUpperCas() !== method.toUpperCase()){
			app.routetable[url] = new build_route.route(method.toUpperCase(), controller, action, args, app.baseUrl);
		}
		else{
			throw new Error("Duplicate Route Found");
		}
	}
});

function httpServer(request, response){
	var body = [];
	var method = request.method;
	response = Router.RouteRequest(request, response, app.routetable);
};